<?php

namespace app\admin\controller;

use think\Config;
use think\Controller;
use think\Session;
use think\Request;

class Login extends Controller {
	//index
	public function index() {
		return $this->fetch('login');
	}

	//login
	public function login($name='',$password='') {

        //判断数据库是否存在此用户
        $admin=Db('operator')->where('name',$name)->find();
        $pass = md5(md5($password).$admin['salt']);
        if($admin){
            //判断用户提交的密码是否与数据库的一致
            if($pass != $admin['password']){
                $this->error("密码错误");
            }else{
//                $_SESSION["admin"]=$admin;
                Session::set('admin',$admin['name']);
                $request = Request::instance();
                $ip=$request->ip();
//                var_dump($_SESSION['admin']);
                //将管理员登录的信息添加到数据库
                $sql = Db('operator')
                    ->where('id', $admin['id'])
                    ->update([
                    'last_time'  =>time(),
                    'logins' => ['exp','logins+1'],
                    'last_ip'=> $ip,
                     ]);
                $this->assign('name','$_SESSION["admin"]');
                $this->success("登录成功","Product/index");
            }
        }


//		if (IS_POST) {
//			$name = (isset($_POST['name']) && trim($_POST['name'])) ? trim($_POST['name']) : '';
//			$password = isset($_POST['password']) ?  $_POST['password'] : '';
//			if ($name =='') error('账户不能为空');
//			if ($password =='') error('密码不能为空');
//			$sql = "SELECT * FROM w_operator WHERE name='{$name}'";
//			$row = $this->db->get_row($sql);
//			if ($row) {
//				$crypt_password = crypt_password($password, $row->salt);
//				if ($crypt_password == $row->password) {
//					$this->admin_id = $row->id;
//					$this->admin_name = $row->name;
//					$_SESSION['admin'] = $row;
//					$sql = "UPDATE w_operator SET last_time='".time()."', last_ip='".ip()."', logins=logins+1 WHERE id='{$row->id}'";
//					$this->db->query($sql);
//					$_SESSION['admin']->last_ip = ip();
//					$_SESSION['admin']->last_time = date("Y-m-d H:i:s",time());
//					header("Location: ?app=home&act=index");
//					exit;
//					//$this->display('home.index.html');
//				} else {
//					exit('username/password is unvalid.');
//				}
//			} else {
//				$this->error('Login failed');
//			}
//		} else {
//			$this->display();
//		}
	}

	public function logout(){
        Session::set('admin');
        Session::clear();
        if (isset($_SESSION['admin'])) unset($_SESSION['admin']);
            session_destroy();
            $this->success("退出成功","login/index");
	}
}